package com.guanghua.brick.html;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guanghua.brick.util.StringUtil;

public class LabelControl extends WebControl {
	
	//private static Log logger = LogFactory.getLog(InputControl.class);
	
	private int newLine = 0;//0表示不换行
	private String dft = null;//默认值
	
	private String textProperty = "text";
	private String valueProperty = "value";
	
	@Override
	public String buildHTML(HttpServletRequest request,
			HttpServletResponse response) {
		//数据初始化
		String label = StringUtil.stringArrayToString(this.getDatas());
		
		//获取content
		label = dealContent(label, request, response);
		
		//默认值
		if (label.length() == 0 && dft != null) label = dft;
		
		//折行
		label = dealNewLine(label);
		
		return label;
	}
	
	/**
	 * 处理content
	 * @param label
	 * @param request
	 * @param response
	 * @return
	 */
	private String dealContent(String label, HttpServletRequest request, HttpServletResponse response) {
		if (this.getContent() != null && label.length() != 0) {
			
			String[] v = this.getDatas();
			String[] d = new String[v.length];
			
			List<Map<String, String>> list = this.getContent().buildContent(request, response);			
			for (int k = 0; k < v.length; k ++) {
				Iterator<Map<String, String>> i = list.iterator();
				while (i.hasNext()) {
					Map<String, String> map = i.next();
					String text = map.get(this.textProperty);
					String value = map.get(this.valueProperty);
					
					if (text == null || value == null) continue;
					
					
					if (value.equals(v[k])) {
						d[k] = text;
						break;
					}
				}
				if (d[k]==null) d[k] = "";
			}
			
			return StringUtil.stringArrayToString(d);
			
		} else {
			return label;
		}
	}
	
	/**
	 * 处理折行
	 * @param label
	 * @return
	 */
	private String dealNewLine(String label) {
		if (newLine > 0 && label.length() != 0) {
			StringBuffer html = new StringBuffer(label);
			for (int i = newLine; i < html.length(); i+=newLine) {
				html.insert(i, "<br>");
				i+=4;
			}	
			return html.toString();
		} else
			return label;
	}

	public String getDefault() {
		return dft;
	}

	public void setDefault(String dft) {
		this.dft = dft;
	}

	public int getNewLine() {
		return newLine;
	}

	public void setNewLine(int newLine) {
		this.newLine = newLine;
	}

	public String getTextProperty() {
		return textProperty;
	}

	public void setTextProperty(String textProperty) {
		this.textProperty = textProperty;
	}

	public String getValueProperty() {
		return valueProperty;
	}

	public void setValueProperty(String valueProperty) {
		this.valueProperty = valueProperty;
	}
	
	
	
}
